//
//  ZJEmotionToolBarView.swift
//  Webo
//
//  Created by 曾静 on 16/7/4.
//  Copyright © 2016年 qq. All rights reserved.
//

import UIKit

@available(iOS 9.0, *)
class ZJEmotionToolBarView: UIStackView {

    var currentBtn:UIButton?
    
    var emotionClourse:((type:EmotionToolBarType)->())?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: -  设置视图
    private func setupUI(){
        
        
        //有两个属性需要事先进行设置
        axis = .Horizontal
        
        distribution = .FillEqually
        
        //添加按钮
        let defaultButton = addToolBarButtons("left", title: "默认",type: .Default)
        
        //设置初始的选中状态
        defaultButton.selected = true
        
        currentBtn = defaultButton
        
        _ = addToolBarButtons("mid", title: "Emoji",type: .Emoji)
        
        _ = addToolBarButtons("right", title: "浪小花",type: .Lxh)
        

        
       
    }
    
    
    func changToolBarSelected(indexPath:NSIndexPath){
        
        let button = self.viewWithTag(indexPath.section + tagMargin)! as! UIButton
        
        if currentBtn == button{
            
            return
        }
        
        //设置按钮的选中状态
        currentBtn?.selected = false
        
        button.selected = true
        
        //可选类型的范围大,可以将对象直接复制给对象的可选类型
        currentBtn = button
        
        
    }
    
    //创建添加按钮的公共方法
    func addToolBarButtons(imageName:String,title:String,type:EmotionToolBarType)->UIButton{
        
        let button = UIButton()
        
        
        button.setBackgroundImage(UIImage(named: "compose_emotion_table_\(imageName)_normal"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "compose_emotion_table_\(imageName)_selected"), forState: UIControlState.Selected)
        
        button.titleLabel?.font = UIFont.systemFontOfSize(15)
        
        button.setTitle(title, forState: UIControlState.Normal)
        
        button.addTarget(self, action: "addToolBarClick:", forControlEvents: UIControlEvents.TouchUpInside)
        
        button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        
        button.setTitleColor(UIColor.grayColor(), forState: UIControlState.Selected)
        
        button.tag = type.rawValue
        //注意添加按钮的方式与UIStackView的区别
        self.addArrangedSubview(button)
        
        return button
    }
    
    func addToolBarClick(button:UIButton){
        
        
        if currentBtn == button{
            
            return
        }
        
        //设置按钮的选中状态
        currentBtn?.selected = false
        
        button.selected = true
        
        //可选类型的范围大,可以将对象直接复制给对象的可选类型
        currentBtn = button
        

        emotionClourse?(type: EmotionToolBarType(rawValue: button.tag)!)
        
        
    }

}
